***************************************************************************
*** REGS COMPARING HOSP TO NBRS WITHIN 100M, OUTCOME = HOSPITAL CLOSURE ***
*** Last edited: 5/3/21         		   	    		***
***************************************************************************
log using "${CodePath}/log/regs_hosp_100m_hospclosure_$S_DATE.log", text replace
use "${DataPath}/within100m/pnlist_groups_100m.dta", clear
duplicates drop hospcomp_group_100 pn, force
expand 9
sort pn
bys pn hospcomp_group_100 : gen fyear = _n + 2006

// create a small dataset with relevant vars
preserve
	use  "${DataPath}/hospital-closures/hospyear_0716_jk_hospclosure.dta", clear
	// fill in missing variables
	tsset pn fyear, yearly

	keep if fyear >= 2007 & fyear <= 2015
	tempfile temp
	save `temp'
restore

merge m:1 pn fyear using `temp', keep(1 3) gen(_jkmerge)


egen hospcomp_group_fyear = group(hospcomp_group_100 fyear)
egen state_splitid = group(state split_id)
egen state_nearseg100 = group(state nearseg100_state)


*--------------------------------------------------
* Regressions on closures of rural hospitals
	* because none of the border hospitals had closed before 2012, can't do event studies
	* instead, regress at the hospital-level whether the hospital had closed by a given year
*-------------------------------------------------- 
// flow: does the hospital close in a given year?
forval y = 2012/2022{
	gen close_in`y' = ever_close & closure_year == `y'
}

cap drop _*
gen _b_=.
gen _min_=.
gen _max_=.
gen _year_= _n + 2012 if _n <= 10

forval y = 2013/2022{
	if `y' != 2017 & `y'!=2021{
	ivreghdfe close_in`y' (audit_in2011 = jk_state_audit_in2011) if fyear == 2011 &urgeo == "RURAL", ///
		absorb(hospcomp_group_fyear) cluster(nearseg100_state_2 state)	
	local i = `y' - 2012
	replace _b_   = _b[audit_in2011]  in `i'
	replace _min_ = _b_ - 1.96*_se[audit_in2011] in `i'
	replace _max_ = _b_ + 1.96*_se[audit_in2011] in `i'
	}
	if `y' == 2017 | `y' == 2021{
		local i = `y' - 2012
		replace _b_   = 0  in `i'
		replace _min_ = 0 in `i'
		replace _max_ = 0 in `i'
	}
	
}

tw ( rcap _min_ _max_ _year_ ) ( scatter _b_ _year_, m(o) ), ///
	legend(off) xtitle("Year", size(large)) ytitle("") ///
	xlabel(2013(1)2022,angle(60) labsize(large)) ///
	ylabel(,labsize(large) angle(horizontal)) ///
	yline(0, lcolor(black) lpattern(dash)) graphregion(color(white))  
graph export "${OutputPath}/RACRegion/jackknife_audit_in2011/hospcomp_100m/Coeffs/ruralhosp_close_inyear.pdf", replace

log close
